package com.guli.shop.config;
/*
 * @Author 罗
 * @date 2020/9/12 - 9:36 上午
 */

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.reactive.CorsConfigurationSource;
import org.springframework.web.cors.reactive.CorsWebFilter;
import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;

/**
 * 跨域配置
 * */
@Configuration
public class CrossDomainConfig {

    @Bean
    public CorsWebFilter corsWebFilter(){
        /**
         * 注意因为gateway底层使用webflix响应式编程，所以需要使用
         * org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource
         * 不要导错包
         * */
        UrlBasedCorsConfigurationSource corsConfigurationSource = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();

        // 允许哪些请求头跨域
        corsConfiguration.addAllowedHeader("*");

        // 允许哪些请求方式可以跨域,get,post,put,delete
        corsConfiguration.addAllowedMethod("*");

        //允许什么请求来源进行跨域
        corsConfiguration.addAllowedOrigin("*");

        // 允许携带cookie进行跨域，不开启，跨域的时候就会丢失cookie信息
        corsConfiguration.setAllowCredentials(true);

        /**
         * 设置任意路径都需要进行跨域
         * */
        corsConfigurationSource.registerCorsConfiguration("/**",corsConfiguration);

        CorsWebFilter corsWebFilter = new CorsWebFilter(corsConfigurationSource);

        return corsWebFilter;
    }

}
